<template>
  <div class="main">
    <a-spin :spinning="loading" tip="loading....">
      <a-card>
        <span class="line">创建问卷</span>
      </a-card>
      <!-- 标题 -->
      <a-card class="cardStyle" hoverable>
        <span style="font-weight: 650;">问卷标题</span>
        <span>
          <a-input
            style="width:300px;margin-left:10px;border:none"
            v-model="title"
            :maxlength="20"
            placeholder="最多输入20个字"
          ></a-input>
        </span>
      </a-card>

      <!-- 题目 -->
      <vuedraggable v-model="questions" :options="{disabled:disabled}">
        <div v-for="(item,index) of questions" :key="index" class="cardStyle">
          <a-card hoverable>
            <!-- 第一行 -->
            <div>
              <span style="position:absolute;">{{index+1}}</span>
              <a-input
                v-model="item.content"
                placeholder="设置问题"
                style="width:400px;border:none;margin-left:30px;margin-top:-5px;resize:none"
                type="textarea"
                autosize
              ></a-input>
              <a-tooltip placement="bottom">
                <div slot="title">
                  <span>逻辑设置</span>
                </div>
                <a-button
                  icon="share-alt"
                  style="position:absolute;right:50%;font-size:20px;margin-left:5px;border:none"
                  @click="logicSet(index)"
                ></a-button>
              </a-tooltip>
              <a-tooltip placement="bottom">
                <div slot="title">
                  <span>复制</span>
                </div>
                <a-button
                  icon="copy"
                  style="position:absolute;right:45%;font-size:20px;margin-left:5px;border:none"
                  @click="copyQusetion(index)"
                ></a-button>
              </a-tooltip>
              <a-tooltip placement="bottom">
                <div slot="title">
                  <span>删除</span>
                </div>
                <a-button
                  icon="delete"
                  style="position:absolute;right:40%;font-size:20px;margin-left:5px;border:none"
                  @click="delQusetion(index)"
                ></a-button>
              </a-tooltip>
              <a-tooltip placement="bottom">
                <div slot="title">
                  <span>拖动开关</span>
                </div>
                <a-button
                  icon="drag"
                  style="position:absolute;right:55%;font-size:20px;margin-left:5px;border:none"
                  @mouseenter="moveDragable"
                  @mouseleave="moveDragable"
                ></a-button>
              </a-tooltip>
            </div>
            <!-- 题目设置 -->
            <vuedraggable v-model="item.choices" :options="{disabled:disabled1}">
              <div style="margin:20px 0;" v-for="(i1,ind1) of item.choices" :key="ind1">
                <div
                  @mouseenter="showDragable1(ind1,index)"
                  @mouseleave="showDragable1"
                  style="width:50%;padding:10px;height:40px;"
                  :style="ind1 === displaydelete&&index===displaydelete2 ? 'outline:1px dashed Gainsboro' : 'border:none'"
                >
                  <a-tooltip v-show="ind1 === displaydelete&&index===displaydelete2">
                    <div slot="title">
                      <span>长按拖动选项</span>
                    </div>
                    <a-icon
                      type="drag"
                      @mouseenter="moveDragable1(ind1,index)"
                      @mouseleave="moveDragable1()"
                      style="position:absolute;fontSize:20px;"
                    ></a-icon>
                  </a-tooltip>
                  <input
                    type="text"
                    v-model="i1.choice"
                    :placeholder="'设置选项'+(ind1+1)"
                    style="width:80%;border:none;margin-left:40px;margin-top:-5px;resize:none;outline:none;"
                  />
                  <a-tooltip v-show="ind1 === displaydelete&&index===displaydelete2">
                    <div slot="title">
                      <span>点击添加选项</span>
                    </div>
                    <a-icon
                      type="plus-circle"
                      style="color: rgba(0,0,0,.45);margin-left:5px;border:none;fontSize:15px;"
                      @click="onAddAnswer(index)"
                    ></a-icon>
                  </a-tooltip>
                  <a-tooltip v-show="ind1 === displaydelete&&index===displaydelete2">
                    <div slot="title">
                      <span>点击删除选项</span>
                    </div>
                    <a-icon
                      type="minus-circle"
                      style="color: rgba(0,0,0,.45);margin-left:15px;border:none;fontSize:15px;"
                      @click="onDelAnswer(index,ind1)"
                    ></a-icon>
                  </a-tooltip>
                </div>
              </div>
            </vuedraggable>

            <!-- 添加选项 -->
            <div style="margin-top:30px;margin-left:50px">
              <a-button icon="plus" style="border:none" @click="onAddAnswer(index)">添加单个选项</a-button>
            </div>

            <!-- 逻辑设置 -->
            <div>
              <a-modal
                title="跳转逻辑"
                v-model="modalformvisible"
                @ok="saveLogic(logicSetIndex)"
                @cancel="cancetlLogic"
                cancelText="取消"
                okText="确认"
                width="700px"
              >
                <div v-for="(from,ind) of choicesForm" :key="ind">
                  请选择题目选项:
                  <a-select v-model="from.choice" placeholder="请选择题目选项" style="width:100px">
                    <a-select-option
                      v-for="(k1,i1) of questions[logicSetIndex].choices"
                      :key="i1"
                    >选项{{i1+1}}</a-select-option>
                  </a-select>请选择跳转题目或图片:
                  <a-select v-model="from.linkToIndex" placeholder="请选择跳转题目" style="width:100px">
                    <a-select-option
                      v-for="(item1,index1) of questions"
                      :key="(index1)"
                    >题目{{index1+1}}</a-select-option>
                    <a-select-option :value="-1">结束图片</a-select-option>
                  </a-select>
                  <span v-if="from.linkToIndex==-1">
                    <a-select v-model="from.bgurl" placeholder="请选择结束图片" style="width:100px">
                      <a-select-option v-for="(img1,inde) of componentData" :key="inde">图片{{inde+1}}</a-select-option>
                    </a-select>
                  </span>
                  <a-button
                    @click="deleteLogic(logicSetIndex,ind)"
                    type="primary"
                    icon="minus-circle"
                    style="margin:0 5px;"
                  ></a-button>
                  <a-button @click="addLogic" type="primary" icon="plus-circle" style="margin:0;"></a-button>
                  <!-- </a-form> -->
                </div>
              </a-modal>
            </div>
          </a-card>
        </div>
      </vuedraggable>

      <!-- 添加问题 -->
      <a-button
        icon="plus"
        style="border:none;margin-top:10px;background:#EDEFF3;"
        @click="onAddQues"
      >添加问题</a-button>

      <!-- 答案图片 -->
      <div style="margin:50px 0 0 10px;">
        <p>设置最终分享的答案图片组</p>
        <!-- 选择答案模块图 -->
        <a-button type="primary" @click="visible1=true">选择答案模块图</a-button>
        <UpChooseImg
          style="margin:20px 0px 20px 10px;display:inline-block"
          :visible1="visible1"
          @UpChooseDate="showcomponentData"
        ></UpChooseImg>
        <!-- 上传答案模块图 -->
        <a-button type="primary" @click="visible2=true">上传答案模块图</a-button>
        <UpdatePoster
          style="margin:20px;display:inline-block"
          :visible2="visible2"
          @UpdatePoster="showcUpdatePoster"
        ></UpdatePoster>

        <!-- 图片模版展示 -->
        <vuedraggable v-model="componentData" :options="{disabled:disabled2}">
          <div v-for="(com1,id1) of componentData" :key="id1" style="display:inline-block">
            <img :src="com1.imgUrl" style="width:100px;height:100px;margin:10px 5px 0 0;" />
          </div>
        </vuedraggable>
      </div>

      <a-button type="primary" style="display:block;margin:100px auto 10px" @click="savePaper">保存</a-button>
    </a-spin>
  </div>
</template>

<script>
import { createPaper, getTmpls, getPaperInfo, getOssPolicy } from "@/api/paper";
import UpChooseImg from "@/components/chooseAnswerTemplateDiagram/UpChooseImg.vue";
import UpdatePoster from "@/components/addAnswerTemplateDiagram/UpdatePoster.vue";
import vuedraggable from "vuedraggable";
import axios from "axios";

import Vue from "vue";

export default {
  name: "create",
  components: {
    UpdatePoster,
    UpChooseImg,
    vuedraggable
  },
  data() {
    return {
      visible2: false,
      visible1: false,
      loading: false,
      componentData: [],
      uid: localStorage.getItem("uid"),
      selectTmpl: {},
      selectTmplindex: "",
      resultTmpls: [],
      flag: false,
      tmplsdata: [],
      title: "",
      type: 0,
      questions: [
        {
          content: "",
          choices: [{ choice: "", linkToIndex: "", bgurl: "" }]
        }
      ],
      result: [],
      shareImageUrls: [],
      logicSetIndex: "",
      modalformvisible: false,
      choicesForm: [],
      disabled: true, //题目拖动开关
      disabled1: true, //选项拖动开关
      disabled2: false, //图片拖动开关
      displaydelete: "", //题目删除显示
      displaydelete2: ""
    };
  },
  watch: {
    type: {
      handler(newtype) {
        if (newtype == 1) {
          this.disabled2 = true;
        } else {
          this.disabled2 = false;
        }
      },
      immediate: true
    }
    // componentData: {
    //   handler(newcom) {
    //     console.log(newcom);
    //   },
    //   immediate: true,
    //   deep:true,
    // }
    // questions:{

    // }
  },
  methods: {
    //逻辑设置
    logicSet(index) {
      var _this = this;
      _this.choicesForm = [];
      _this.logicSetIndex = index;
      _this.modalformvisible = true;
      var _item = _this.questions[index].choices;
      Object.keys(_item).forEach(key => {
        if (_item[key].linkToIndex != 0) {
          var arr = { choice: "", linkToIndex: "", bgurl: "" };
          var _key = Number(key);
          arr.choice = _key;
          arr.linkToIndex = _item[key].linkToIndex;
          arr.bgurl = _item[key].bgurl;
          _this.choicesForm.push(arr);
        }
      });
      if (_this.choicesForm == "") {
        var arr = { choice: "", linkToIndex: "", bgurl: "" };
        _this.choicesForm.push(arr);
      }
      console.log(_this.questions[_this.logicSetIndex].choices);
    },
    //添加逻辑
    addLogic() {
      var arr = { choice: "", linkToIndex: "", bgurl: "" };
      this.choicesForm.push(arr);
    },
    //删除逻辑
    deleteLogic(index, ind) {
      var i = this.choicesForm[ind].choice;
      if (i >= 0) {
        console.log(this.questions[index]);
        if (
          this.questions[index] != undefined &&
          this.questions[index].choices[i] != undefined &&
          this.questions[index].choices[i].linkToIndex != undefined
        ) {
          this.questions[index].choices[i].linkToIndex = 0;
          this.questions[index].choices[i].bgurl = "";
        }
      }
      this.choicesForm.splice(ind, 1);
      if (this.choicesForm.length == 0) {
        var arr = { choice: "", linkToIndex: "", bgurl: "" };
        this.choicesForm.push(arr);
      }
    },
    //保存逻辑
    saveLogic(index) {
      var _this = this;
      var _item = _this.questions[index].choices;
      var _item1 = _this.choicesForm;
      if (_item1.length == 0) {
        _this.$message.error("没有可以保存的逻辑");
      }
      Object.keys(_item1).forEach(key => {
        if (parseInt(_item1[key].choice) >= 0) {
          if (_item1[key].linkToIndex >= 0 || _item1[key].linkToIndex <= 0) {
            if (parseInt(index) == parseInt(_item1[key].linkToIndex)) {
              _this.$message.error("不能跳转本题，请选择其他题目");
              _item1[key].linkToIndex = "";
            } else {
              if (parseInt(_item1[key].linkToIndex) == -1) {
                if (parseInt(_item1[key].bgurl) >= 0) {
                  _item[_item1[key].choice].linkToIndex =
                    _item1[key].linkToIndex;
                  _item[_item1[key].choice].bgurl = _item1[key].bgurl;
                  if (Number(key) == _item1.length-1) {
                    this.modalformvisible = false;
                  }
                  console.log(_this.questions);
                } else if (
                  _item1[key].bgurl == "" ||
                  _item1[key].bgurl == undefined
                ) {
                  let _key = _item1[key].choice + 1;
                  this.$message.error("第" + _key + "选项未选定图片,添加跳转图片失败");
                }
              } else {
                _item[_item1[key].choice].linkToIndex = _item1[key].linkToIndex;
                _item[_item1[key].choice].bgurl = _item1[key].bgurl;
                this.modalformvisible = false;
                console.log(_this.questions);
              }
            }
          } else {
            _this.$message.error("有跳转题目未选定");
          }
        } else {
          _this.$message.error("有选项未选定");
        }
      });
    },
    //取消逻辑
    cancetlLogic() {
      this.choicesForm = [];
      this.modalformvisible = false;
    },
    //复制问题
    copyQusetion(index) {
      var arr = JSON.parse(JSON.stringify(this.questions[index]));
      this.questions.splice(index, 0, arr);
    },
    //删除问题
    delQusetion(index) {
      if (this.questions.length <= 1) {
        this.$message.error("至少有一个问题，不能删除");
      } else {
        if (this.choicesForm.length > 0) {
          this.choicesForm.splice(0, this.choicesForm.length);
        }
        this.questions.splice(index, 1);
      }
    },
    //问题移动问题
    moveDragable() {
      this.disabled = !this.disabled;
    },
    //选项移动问题
    moveDragable1(ind, index) {
      this.disabled1 = !this.disabled1;
      if (ind >= 0) {
        this.displaydelete = ind;
        this.displaydelete2 = index;
      } else {
        this.displaydelete = "";
        this.displaydelete2 = "";
      }
    },
    //选项显示问题
    showDragable1(ind, index) {
      // this.disabled1 = !this.disabled1;
      if (ind >= 0) {
        this.displaydelete = ind;
        this.displaydelete2 = index;
      } else {
        this.displaydelete = "";
        this.displaydelete2 = "";
      }
    },
    //添加问题
    onAddQues() {
      var obj = {
        content: "",
        choices: [{ choice: "", linkToIndex: "", bgurl: "" }]
      };
      this.questions.push(obj);
    },
    //删除回答选项
    onDelAnswer(index, i) {
      if (this.questions[index].choices.length <= 1) {
        this.$message.error("至少有一个选项，不能删除");
      } else {
        this.questions[index].choices.splice(i, 1);
      }
    },
    //添加回答选项
    onAddAnswer(index) {
      var arr = { choice: "", linkToIndex: "", bgurl: "" };
      this.questions[index].choices.push(arr);
      console.log(this.questions);
    },
    //拖动图片
    swicthPosition(OldPositon, NewPositon, originItem) {
      console.log(OldPositon, NewPositon, originItem);
      if (OldPositon && NewPositon) {
        this.componentData.splice(
          NewPositon - 1,
          0,
          this.componentData.splice(OldPositon - 1, 1)[0]
        );
      }
      console.log(this.componentData);
    },
    //获取选择图片子组件的值
    showcomponentData(value, data) {
      var _this = this;
      if (data != undefined) {
        if (data) {
          _this.componentData = data;
          Vue.set(_this.componentData, data);
          _this.changeTemplateToClear();
        }
        console.log(_this.questions);
      }
      if (value) {
        _this.visible1 = value;
      } else {
        _this.visible1 = false;
      }
    },
    //获取添加图片子组件的值
    showcUpdatePoster(value, data1) {
      var _this = this;
      if (data1 != undefined) {
        if (data1) {
          _this.componentData = data1;
          Vue.set(_this.componentData, data1);
          _this.changeTemplateToClear();
        }
        console.log(_this.questions);
      }
      if (value) {
        _this.visible2 = value;
      } else {
        _this.visible2 = false;
      }
    },
    //保存所有
    savePaper() {
      var _this = this;
      if (_this.title == "") {
        _this.$message.error("标题不能为空");
        return;
      }
      for (let q of _this.questions) {
        // console.log(q);
        if (q["content"].trim().length == 0) {
          _this.$message.error("有问题为空");
          return;
        }
        for (let j of q["choices"]) {
          if (j.choice == "") {
            _this.$message.error("有选项为空");
            return;
          } else {
            if (parseInt(j.linkToIndex) >= 1 || parseInt(j.linkToIndex) == -1) {
              // console.log(j.linkToIndex)
            } else {
              j.linkToIndex = 0;
            }
          }
        }
      }
      if (Object.keys(_this.componentData).length == 0) {
        _this.$message.error("还没选择图片");
        return;
      }
      //验证paperid（判断是新建还是查看）
      if (!this.$route.query.paperId) {
        _this.loading = true;
        _this.shareImageUrls = [];
        for (var i = 0; i < _this.componentData.length; i++) {
          //验证图片为http或者base64（为base64上传oss）
          if (_this.componentData[i]["imgUrl"].includes("http")) {
            _this.shareImageUrls.push(_this.componentData[i]["imgUrl"]);
            _this.dataValidation1();
          } else {
            var filet = _this.dataURLtoFile(
              _this.componentData[i]["imgUrl"],
              "textbg" + i + ".jpg"
            );
            _this.upload(filet, i, function(imgurl) {
              _this.shareImageUrls.push(imgurl);
              _this.dataValidation1();
            });
          }
        }
      } else {
        _this.loading = true;
        _this.shareImageUrls = [];
        for (var i1 = 0; i1 < _this.componentData.length; i1++) {
          if (_this.componentData[i1]["imgUrl"].includes("http")) {
            _this.shareImageUrls.push(_this.componentData[i1]["imgUrl"]);
            _this.dataValidation2();
          } else {
            var filet1 = _this.dataURLtoFile(
              _this.componentData[i1]["imgUrl"],
              "textbg" + i1 + ".jpg"
            );
            _this.upload(filet1, i1, function(imgurl) {
              _this.shareImageUrls.push(imgurl);
              _this.dataValidation2();
            });
          }
        }
      }
    },
    //选择模版图片清除
    changeTemplateToClear() {
      var _this = this;
      for (let qs of _this.questions) {
        for (let qs1 of qs.choices) {
          qs1.bgurl = "";
        }
      }
      if (_this.type == 1) {
        _this.$message.error(
          "你更改了答案模版，导向结果答案的选项已重置，请重新选择选项的答案图片"
        );
        Object.keys(_this.questions).forEach(key => {
          Object.keys(_this.questions[key].choices).forEach(key1 => {
            var _bg = _this.questions[key].choices[key1];
            if (Number(_bg.linkToIndex) == -1) {
              _this.questions[key].choices[key1].bgurl = "";
              _this.questions[key].choices[key1].linkToIndex = 0;
            }
          });
        });
      }
    },
    //没有paperId验证
    dataValidation1() {
      var _this = this;
      if (_this.shareImageUrls.length == _this.componentData.length) {
        let data = {
          uid: _this.uid,
          title: _this.title,
          shareImageTemplateId: _this.componentData[0]["tmplId"],
          shareImageUrls: _this.shareImageUrls,
          questions: JSON.parse(JSON.stringify(_this.questions)),
          type: _this.type
        };
        for (let q of data.questions) {
          for (let j of q["choices"]) {
            if (parseInt(j.bgurl) >= 0) {
              j.bgurl = data.shareImageUrls[j.bgurl];
            }
            if (parseInt(j.linkToIndex) >= 1 || parseInt(j.linkToIndex) == -1) {
              data.type = 1;
              _this.type = 1;
            }
          }
        }
        if (data.type == 1) {
          for (let jk of data.questions[data.questions.length - 1].choices) {
            if (jk.bgurl == "") {
              _this.$message.error("最后一题请选择选项逻辑图片");
              _this.loading = false;
              return;
            }
          }
          Object.keys(data.questions).forEach(key => {
            Object.keys(data.questions[key].choices).forEach(key1 => {
              var _it = data.questions[key].choices[key1];
              console.log(_it);
              if (_it.linkToIndex == 0) {
                data.questions[key].choices[key1].linkToIndex = Number(key) + 1;
              }
            });
          });
        }
        console.log(data);

        createPaper(data)
          .then(res => {
            console.log(res, "保存成功");
            if (res.msg) {
              _this.$message.success(res.msg);
              _this.$router.push({
                path: "/public/paper/UserPaper"
              });
            }
            _this.loading = false;
          })
          .catch(err => {
            _this.$message.error(err);
            _this.loading = false;
          });
      }
    },
    //有paperid验证
    dataValidation2() {
      var _this = this;
      if (_this.shareImageUrls.length == _this.componentData.length) {
        let data = {
          uid: _this.uid,
          title: _this.title,
          paperId: _this.$route.query.paperId,
          shareImageTemplateId: _this.componentData[0]["tmplId"],
          shareImageUrls: _this.shareImageUrls,
          questions: JSON.parse(JSON.stringify(_this.questions)),
          type: _this.type
        };
        var _length1 = data.questions.length - 1;
        for (var il1 = 0; il1 < _length1; il1++) {
          var _length2 = data.questions[il1]["choices"].length;
          for (var j1 = 0; j1 < _length2; j1++) {
            if (
              parseInt(data.questions[il1]["choices"][j1].linkToIndex) >= 1 ||
              parseInt(data.questions[il1]["choices"][j1].linkToIndex) == -1
            ) {
              data.type = 1;
              _this.type = 1;
            }
          }
        }
        Object.keys(data.questions).forEach(key => {
          Object.keys(data.questions[key].choices).forEach(key1 => {
            var _bg = data.questions[key].choices[key1];
            if (Number(_bg.linkToIndex) == -1) {
              if (Number(_bg.bgurl) >= 0) {
                data.questions[key].choices[key1].bgurl =
                  data.shareImageUrls[Number(_bg.bgurl)];
                console.log(data.questions);
              }
            }
          });
        });
        console.log(data.type)
        Object.keys(data.questions).forEach(key => {
          Object.keys(data.questions[key].choices).forEach(key1 => {
            var _bg = data.questions[key].choices[key1];
            if (_bg.linkToIndex > 0 || _bg.linkToIndex == -1) {
              _this.type = 1;
              data.type = 1;
            }
            if (
              _this.type == 0 &&
              data.type == 0 &&
              _bg.linkToIndex == 0 &&
              Number(key) + 1 == data.questions.length
            ) {
              _this.type = 0;
              data.type = 0;
            }
          });
        });
        console.log(data.type)
        if (data.type == 0) {
          var _index1 = data.questions.length - 1;
          var _Length1 = data.questions[_index1]["choices"].length;
          for (var j2 = 0; j2 < _Length1; j2++) {
            if (
              data.questions[_index1]["choices"][j2].bgurl == "" ||
              data.questions[_index1]["choices"][j2].bgurl == undefined
            ) {
              data.type = 0;
              _this.type = 0;
            }else{
              data.type = 1;
              _this.type = 1;
            }
          }
        }
        console.log(data.type)
        console.log(_this.questions)
        var  _sum=0;
        Object.keys(data.questions).forEach(key => {
            Object.keys(data.questions[key].choices).forEach(key1 => {
              var _it = data.questions[key].choices[key1];
              _sum=_sum+parseInt(_it.linkToIndex);
            });
          });
          if(_sum==0){
            data.type = 0;
            this.type =0;
          }
        if (data.type == 1) {
          for (let jk1 of data.questions[data.questions.length - 1].choices) {
            if (jk1.bgurl == "") {
              _this.$message.error("最后一题请选择选项逻辑图片");
              _this.loading = false;
              return;
            }
          }
          Object.keys(data.questions).forEach(key => {
            Object.keys(data.questions[key].choices).forEach(key1 => {
              var _it = data.questions[key].choices[key1];
              if (_it.linkToIndex == 0) {
                data.questions[key].choices[key1].linkToIndex = Number(key) + 1;
              }
            });
          });
        }
        console.log(data);

        createPaper(data)
          .then(res => {
            console.log(res, "保存成功");
            if (res.msg) {
              _this.$message.success(res.msg);
              _this.$router.push({
                path: "/public/paper/UserPaper"
              });
            }
            _this.loading = false;
          })
          .catch(err => {
            _this.$message.error(err);
            _this.loading = false;
          });
      }
    },
    //上传oss
    async upload(file, idx, fun) {
      var _this = this;
      console.log(file);
      let json;
      await getOssPolicy({}).then(res => {
        json = res;
      });
      console.log(json);
      var AuthMsg = json;
      console.log(AuthMsg);
      var arrIndex = file.name.split(".").length - 1;
      var imgExit = file.name.split(".")[arrIndex];
      // var rand = new Date().getTime() + Math.floor(Math.random() * 150);
      var rand = _this.getCode();
      var ossKey = AuthMsg.dir + rand + "_" + idx + "." + imgExit;
      var imgurl = AuthMsg.host + "/" + ossKey;
      // // 添加签名信息
      var ossData = new FormData();
      ossData.append("OSSAccessKeyId", AuthMsg.accessid);
      ossData.append("policy", AuthMsg.policy);
      ossData.append("Signature", AuthMsg.signature);
      ossData.append("key", ossKey);
      // // 添加文件
      ossData.append("file", file, rand);
      ossData.append("success_action_status", 200);
      let config = {
        headers: {
          "Content-Type": "application/octet-stream"
        }
      }; //添加请求头
      axios
        .post(AuthMsg.host, ossData, config)
        .then(function(response) {
          console.log(response);
          fun(imgurl);
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    // 数据转换
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    // 随机码
    getRandom(min, max) {
      return Math.round(Math.random() * (max - min) + min);
    },
    getCode() {
      var _this = this;
      let code = "";
      for (var i = 0; i < 6; i++) {
        var type = _this.getRandom(1, 3);
        switch (type) {
          case 1:
            code += String.fromCharCode(_this.getRandom(48, 57)); //数字
            break;
          case 2:
            code += String.fromCharCode(_this.getRandom(65, 90)); //大写字母
            break;
          case 3:
            code += String.fromCharCode(_this.getRandom(97, 122)); //小写字母
            break;
        }
      }
      return code;
    }
  },
  //获取所有数据
  mounted() {
    var _this = this;

    var data = { uid: _this.uid };
    // 获取图片模版
    getTmpls(data)
      .then(res => {
        console.log(res.data, "getTmpls");
        _this.tmplsdata = res.data.templates;
      })
      .catch(err => console.log(err));
    //编辑进入进行数据处理
    if (this.$route.query.paperId) {
      let data = {
        paperId: this.$route.query.paperId
      };
      getPaperInfo(data)
        .then(res => {
          //数据处理
          console.log(res.data, "getPaperInfo");
          if (res.data) {
            var info = res.data;
            _this.title = info.title;
            _this.shareImageTemplateId = info.shareImageTemplateId;
            _this.shareImageUrls = info.resultImgs;
            _this.result = info.resultImgs;
            for (let i = 1; i <= _this.result.length; i++) {
              let data = {
                positionNum: i,
                id: "card" + i,
                name: "1",
                tmplId: _this.shareImageTemplateId,
                imgUrl: _this.result[i - 1]
              };
              _this.componentData.push(data);
            }
            _this.questions = [];
            _this.questions = info.questions;
            for (let q of info.questions) {
              for (let q1 of q.choices) {
                for (let key in q1) {
                  if (key == "content") {
                    q1["choice"] = q1[key];
                    delete q1[key];
                  }
                }
              }
            }
            Object.keys(_this.questions).forEach(key => {
              Object.keys(_this.questions[key].choices).forEach(key1 => {
                let _i = _this.questions[key].choices[key1];
                if (_i.linkToIndex >= 0) {
                  var _key = Number(key) + 1;
                  if (_key == _i.linkToIndex) {
                    _this.type = 0;
                  } else {
                    _this.type = 1;
                  }
                } else if (_i.linkToIndex == -1) {
                  var _key1 = Number(key) + 1;
                  if (_key1 != _this.questions.length) {
                    _this.type = 1;
                  } else {
                    if (
                      _this.questions[key].choices[key1].bgurl == "" ||
                      _this.questions[key].choices[key1].bgurl == undefined
                    ) {
                      _this.type = 0;
                      _this.questions[key].choices[key1].linkToIndex = 0;
                      _this.questions[key].choices[key1].bgurl = "";
                    } else {
                      _this.type = 1;
                    }
                  }
                }
              });
            });
            if (_this.type == 0) {
              Object.keys(_this.questions).forEach(key => {
                Object.keys(_this.questions[key].choices).forEach(key1 => {
                  _this.questions[key].choices[key1].linkToIndex = 0;
                });
              });
            }
          }
          console.log(_this.questions);
        })
        .catch(err => console.log(err));
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .ant-layout-content {
  margin: 0;
}

.main {
  position: relative;
  width: 100%;
  text-align: left;
  height: 100%;
  .line {
    border-left: 5px solid #1890ff;
    padding-left: 10px;
    font-weight: 500;
    font-size: 16px;
  }
  .cardStyle {
    margin: 30px 0;
    border-radius: 10px;
  }
}
</style>